﻿using SautinSoft;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Http;

namespace NCP.Recruiting.Web.Framework
{
    public static class HtmlConvrtWord
    {
        public static void DownloadWord(this HttpContext context, string url, string filename)
        {
            HtmlToRtf word = new HtmlToRtf();
            
            //word.Serial
            word.PageStyle.PageNumbers.Appearance = HtmlToRtf.ePageNumbers.PageNumFirst;
            string htmlString = GetHtmlFromView(url);
            
            var wordString = word.ConvertString(htmlString);

            if (wordString != "")
            {
                context.Response.Buffer = true;
                context.Response.Clear();
                context.Response.ContentType = "application/msword";
                context.Response.AddHeader("content-disposition", "inline; filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));
                context.Response.Write(wordString);
                context.Response.Flush();
                context.Response.End();
            }
        }

        public static string GetHtmlFromView(string url)
        {
            string contents = "";

            if (url.Length > 6)
            {
                Stream streamHttp = null;
                WebResponse resp = null;
                HttpWebRequest webrequest = null;
                try
                {
                    webrequest = (HttpWebRequest)WebRequest.Create(url);
                    resp = webrequest.GetResponse();
                    streamHttp = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(streamHttp);
                    contents = sr.ReadToEnd();
                    return contents;
                }
                catch
                {
                }
            }
            return contents;
        }
    }
}
